package com.xncoding.pos.nacos;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.cloud.nacos.NacosConfigManager;
import com.alibaba.cloud.nacos.NacosConfigProperties;
import com.alibaba.nacos.api.config.ConfigService;
import com.alibaba.nacos.api.config.annotation.NacosConfigListener;
import com.alibaba.nacos.api.exception.NacosException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;
import org.yaml.snakeyaml.Yaml;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
 * 初始化加载nacos里的配置文件
 *
 * @Author guoyb
 * @Date 2020/11/6  11:03
 */
@Component
@Slf4j
@ConditionalOnProperty(value = "spring.cloud.nacos.config.enabled", havingValue = "true")
public class MyNacosListen extends BaseNacosConfig {

    @Resource
    NacosConfigManager nacosConfigManager;

    String dataId = "nacos-config-advanced.yml";
    String group = "DEFAULT_GROUP";

    @PostConstruct
    public void init() throws NacosException {
        ConfigService configService = nacosConfigManager.getConfigService();

        NacosConfigProperties nacosConfigProperties = nacosConfigManager.getNacosConfigProperties();
        log.info("初始化加载-----nacosConfigProperties------{}", nacosConfigProperties.getServerAddr());

        super.init(configService, dataId, group);

    }


    @Override
    protected void parseConfig(String config) {
        HashMap hashMap = null;
        try {
            if (StrUtil.isNotBlank(config)) {
                Yaml yaml = new Yaml();
                Map obj = yaml.load(config);
                Map<String, Object> param = new HashMap<>();
                //需要注意，此类加载器只能得到它的最顶层的key的值
                Map<String, Object> params = (Map) obj.get("ctfo");
                param.putAll(params);
                System.out.println("params = " + params);

                Map<String, Object> params11 = (Map) params.get("parking");
                Object orgCodes = params11.get("orgCodes");



                Map<String, Object> params2 = (Map) obj.get("server");
                param.putAll(params2);
                System.out.println("params2 = " + params2);
                System.out.println("param = " + param);

                // hashMap = JacksonUtils.json2pojo(config, HashMap.class);
                // log.info("config-----打印日志------{}", hashMap);
            }

        } catch (Exception e) {
            log.error("parseConfig异常信息:{}", e.getMessage());
        }
    }


    /**
     * 通过注解配置监听器
     * 配置转换为Properties类型
     *
     * @param value
     */
    @NacosConfigListener(dataId = "nacos-config-advanced")
    public void onReceived(String value) {
        log.info("监听1-----打印日志------{}", JSONUtil.toJsonStr(value));

    }


}